package com.zzyl.service.impl;

import com.zzyl.dto.UserLoginRequestDto;
import com.zzyl.entity.Member;
import com.zzyl.mapper.MemberMapper;
import com.zzyl.properties.JwtTokenConfigProperties;
import com.zzyl.service.CostomerLongService;
import com.zzyl.service.WechatService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
public class CostomerLongServiceimpl implements CostomerLongService {
    @Autowired
    private WechatService wechatService;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private JwtTokenConfigProperties jwtTokenConfigProperties;

   @Override
   public LoginVo login(UserLoginRequestDto userLoginRequestDto) {
       String openId = wechatService.getOpenId(userLoginRequestDto.getCode());
       String phoneNumber =  wechatService.getPhone(userLoginRequestDto.getPhoneCode());
       Member member = memberMapper.getMemberByOpenId(openId);
      /* if (ObjectUtil.isEmpty(member)){
           member=new Member();
           member.setOpenId(openId);
       }


        if (!member.getPhone().equals(phoneNumber)){
            member.setPhone(phoneNumber);
        }

        if (ObjectUtil.isNotNull(member.getId())){
            memberMapper.update(member);
        }else {
           member= new Member();
           member.setOpenId(openId);
            member.setPhone(phoneNumber);
            member.setName("00000000");
            memberMapper.inster(member);
        }


       //token
       HashMap<String, Object> map = new HashMap<>();
        map.put("userid", member.getId());
        map.put("name", member.getName());
       String token = JwtUtil.createJWT(jwtTokenConfigProperties.getBase64EncodedSecretKey(), jwtTokenConfigProperties.getTtl(), map);
       LoginVo loginVo = new LoginVo();
       loginVo.setToken(token);
       loginVo.setNickName(member.getName());

       return loginVo;*/
       if (ObjectUtil.isNotNull(member)){//member不为空，判断手机号是否相同
           if(!ObjectUtil.equals(member.getPhone(),phoneNumber)){
               member.setPhone(phoneNumber);
               memberMapper.update(member);
           }
       }else {//member为空，创建新用户
           member=new Member();
           member.setOpenId(openId);
           member.setPhone(phoneNumber);
            member.setName("张三");
           memberMapper.inster(member);
       }
       //token
       HashMap<String, Object> map = new HashMap<>();
       map.put("userid", member.getId());
       String token = JwtUtil.createJWT(jwtTokenConfigProperties.base64EncodedSecretKey, jwtTokenConfigProperties.getTtl(), map);
       LoginVo loginVo = new LoginVo();
       loginVo.setToken(token);
       loginVo.setNickName(member.getName());

       return loginVo;
   }

   



}
